package com.manli.api.base.aop;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.manli.api.base.exception.MyException;
import com.manli.api.enums.ResultEnums;
import com.manli.api.pojo.Result;
import com.manli.api.pojo.SessionInfo;
import com.manli.api.util.IPUtils;
import com.manli.api.util.ResultUtil;
import com.manli.api.util.SessionInfoUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 拦截Action请求
 * @author Shensg
 * 2018年5月31日
 */
@Aspect
@Component
public class HttpAspect {
	private Logger logger = LoggerFactory.getLogger(HttpAspect.class);  
	  
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Autowired
    SessionInfoUtils sessionInfoUtils;
  
    @Pointcut("execution(* com.manli.api.controller..*Controller.*(..))")
    public void webLog(){}  
  
    @Before("webLog()")  
    public void doBefore(JoinPoint joinPoint) throws Throwable {  
        startTime.set(System.currentTimeMillis());  
  
        // 接收到请求，记录请求内容  
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  
        HttpServletRequest request = attributes.getRequest();  
  
        // 记录下请求内容
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        if(sessionInfo!=null){
            //谁 使用多少IP 调用什么方法 参数是什么
            if(sessionInfo.getWeChatUserInfo() != null){
                logger.info("[入]-[微信端访问]-人员[{}]-IP[{}]-请求地址[{}]-请求参数[{}]",
                        sessionInfo.getWeChatUserInfo().getOpenid()+" "+sessionInfo.getWeChatUserInfo().getNickname(),
                        IPUtils.getRealIP(request),
                        request.getRequestURL().toString() +" "+ request.getMethod(),
                        Arrays.toString(joinPoint.getArgs()));
            }else{
                logger.info("[入]-[后台管理访问]-人员[{}]-IP[{}]-请求地址[{}]-请求参数[{}]",
                        sessionInfo.getUserId()+" " + sessionInfo.getName(),
                        IPUtils.getRealIP(request),
                        request.getRequestURL().toString() +" "+ request.getMethod(),
                        Arrays.toString(joinPoint.getArgs()));
            }
        }else{
            logger.info("[入]-[开放接口访问]-IP[{}]-请求地址[{}]-请求参数[{}]",
                    IPUtils.getRealIP(request),
                    request.getRequestURL().toString() +" "+ request.getMethod(),
                    Arrays.toString(joinPoint.getArgs()));
        }
        /*logger.info("HttpAspect.doBefore 切面到Action");
        logger.info("URL=" + request.getRequestURL().toString());  
        logger.info("HTTP_METHOD=" + request.getMethod());
        logger.info("CLASS_METHOD=" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());  
        logger.info("ARGS=" + Arrays.toString(joinPoint.getArgs()));*/

    }

  
    @AfterReturning(returning = "ret", pointcut = "webLog()")  
    public void doAfterReturning(JoinPoint joinPoint,Object ret) throws Throwable {
        if(ret instanceof Result){
            ret = JSONObject.toJSONString(ret);
        }
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求响应内容
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        if(sessionInfo!=null){
            //谁 使用多少IP 调用什么方法 参数是什么
            if(sessionInfo.getWeChatUserInfo() != null){
                logger.info("[出]-[微信端访问]-人员[{}]-IP[{}]-请求地址[{}]-响应参数[{}]",
                        sessionInfo.getWeChatUserInfo().getOpenid()+" "+sessionInfo.getWeChatUserInfo().getNickname(),
                        IPUtils.getRealIP(request),
                        request.getRequestURL().toString() +" "+ request.getMethod(),
                        ret);
            }else{
                logger.info("[出]-[后台管理访问]-人员[{}]-IP[{}]-请求地址[{}]-响应参数[{}]",
                        sessionInfo.getUserId()+" " + sessionInfo.getName(),
                        IPUtils.getRealIP(request),
                        request.getRequestURL().toString() +" "+ request.getMethod(),
                        ret);
            }
        }else{
            logger.info("[出]-[开放接口访问]-IP[{}]-请求地址[{}]-响应参数[{}]",
                    IPUtils.getRealIP(request),
                    request.getRequestURL().toString() +" "+ request.getMethod(),
                    ret);
        }
    }

    @AfterThrowing(pointcut = "webLog()", throwing = "ex")
    public void doAfterThrowing(JoinPoint joinPoint, Exception ex) {
        String ret = null;
        if (ex instanceof MyException) {
            ret = ((MyException)ex).getMessage();
        }else {
            logger.error("【系统异常】"+ex.getStackTrace());
            ret = getExceptionToString(ex);
        }


        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求响应内容
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        if(sessionInfo!=null){
            //谁 使用多少IP 调用什么方法 参数是什么
            if(sessionInfo.getWeChatUserInfo() != null){
                logger.error("[出]-[微信端访问]-人员[{}]-IP[{}]-请求地址[{}]-入参[{}]-异常[{}]",
                        sessionInfo.getWeChatUserInfo().getOpenid()+" "+sessionInfo.getWeChatUserInfo().getNickname(),
                        IPUtils.getRealIP(request),
                        request.getRequestURL().toString() +" "+ request.getMethod(),
                        Arrays.toString(joinPoint.getArgs()),
                        ret);
            }else{
                logger.error("[出]-[后台管理访问]-人员[{}]-IP[{}]-请求地址[{}]-入参[{}]-异常[{}]",
                        sessionInfo.getUserId()+" " + sessionInfo.getName(),
                        IPUtils.getRealIP(request),
                        request.getRequestURL().toString() +" "+ request.getMethod(),
                        Arrays.toString(joinPoint.getArgs()),
                        ret);
            }
        }else{
            logger.error("[出]-[开放接口访问]-IP[{}]-请求地址[{}]-入参[{}]-异常[{}]",
                    IPUtils.getRealIP(request),
                    request.getRequestURL().toString() +" "+ request.getMethod(),
                    Arrays.toString(joinPoint.getArgs()),
                    ret);
        }
    }

    public String getExceptionToString(Throwable e) {
        if (e == null){
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }
}
